const express = require('express')
const router = express.Router()
const fs = require('fs')
const path = require('path')

// 临时分片存储目录
const TEMP_DIR = path.join(__dirname, 'temp')
const UPLOAD_DIR = path.join(__dirname, 'uploads')

// 确保目录存在
if (!fs.existsSync(TEMP_DIR)) fs.mkdirSync(TEMP_DIR)
if (!fs.existsSync(UPLOAD_DIR)) fs.mkdirSync(UPLOAD_DIR)

router.post('/', (req, res) => {
  const { fileHash } = req.query

  // console.log(fileHash)

  // 文件 hash 作为唯一上传ID
  const uploadId = fileHash

  // 创建临时目录
  const tempDir = path.join(TEMP_DIR, uploadId)
  if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir)
  
  // 检查是否已有上传记录
  const chunkDir = path.join(tempDir, 'chunks')
  let uploadedChunks = []
  
  if (fs.existsSync(chunkDir)) {
    uploadedChunks = fs.readdirSync(chunkDir)
      .map(name => parseInt(name.replace('chunk-', '')))
      .filter(num => !isNaN(num))
      .sort((a, b) => a - b)
  } else {
    fs.mkdirSync(chunkDir)
  }

  res.send({
    code: 200,
    message: 'success',
    data: {
      uploadId,
      uploadedChunks
    }
  })
})

module.exports = router
